package com.peanutplan.blog.utils;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class GoogleTransLanguageResourceGetUtil {
	
	public static void main(String[] args) {
		List<String> ls = LanguageUtil.getShortLanguages();
		Set<String> languages = new HashSet<>();
		
		ExecutorService p = Executors.newFixedThreadPool(ls.size());
		List<Future<String>> futures = new ArrayList<Future<String>>(ls.size());
		for(String language:ls) {
			futures.add(p.submit(new Fetch(language)));
		}
		
		for(Future<String> f:futures) {
			String r = null;
			try {
				r = f.get();
			}catch(Exception e) {
				e.printStackTrace();
			}
			if(r!=null) {
				languages.add(r);
			}
		}
		p.shutdown();
		String newStr = String.join(",", languages);
		System.out.println("共"+languages.size()+"种语言");
		System.out.println(newStr);
	}
	
}
class Fetch implements Callable<String> {

	private String language;
	
	public Fetch() {}
	
	public Fetch(String language) {
		this.language = language;
	}

	@Override
	public String call() throws Exception {
		String r = null;
		
		String fileName = "main_" + language + ".js";
		String str = HttpClientUtil.httpGetRequest("https://translate.googleapis.com/translate_static/js/element/"+fileName);
		
		if(!str.startsWith("<!DOCTYPE html>")) {
			String preFix = ".src=";
			int preFixIndex = str.indexOf(preFix)+preFix.length();
			
			String pre = str.substring(0, preFixIndex);
			
			String next = str.substring(preFixIndex);
			next = next.substring(next.indexOf(";"));

			str = pre+"resourcesUrl+\"/js/element_main.js\""+next;
			
			File fp = new File("C:\\Users\\motisy\\Desktop\\la\\" + fileName);
			if (!fp.exists()) {
				try {
					fp.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		    try (PrintStream stream=new PrintStream(fp.getPath())) {
		        stream.print(str);//写入的字符串
		    } catch (Exception e) {
		        e.printStackTrace();
		    }
		    r = language;
		}else {
			System.out.println(language+"不存在！");
		}
		
		return r;
	}
}
